<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/9/18
 * Time: 17:33
 */
class PopupApp extends BackendApp
{
    protected $_popup_mod;
    protected $_banner_setting_mod;
    protected $_theme_setting_mod;

    function __construct()
    {
        $this->PopuApp();
    }

    function PopuApp()
    {
        parent::BackendApp();
        $this->_popup_mod = &m('popup');
        $this->_banner_setting_mod = &m('banner_setting');
        $this->_theme_setting_mod = &m('theme_setting');
    }

    //列表
    function index(){
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'type',
                'equal' => '=',
            ),
            array(
                'field' => 'status',
                'equal' => 'like',
            ),
        ));

        $page = $this->_get_page(10);
        $res = $this->_popup_mod->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "id desc"
        ));

        //格式化type 、status  字段
        foreach($res as $k=>$v){
            if($v['type'] == 'banner'){
                $info = $this->_banner_setting_mod->get(array("conditions"=>"banner_id = ".$v['popup_id']));
                $res[$k]['title'] = $info['banner_remark'];
            }else{
                $info = $this->_theme_setting_mod->get(array("conditions"=>"theme_id = ".$v['popup_id']));
                $res[$k]['title'] = $info['theme_title'];
            }
            //类型
            $res[$k]['type_value'] = PopupModel::$typeValue[$v['type']];
            //定义状态
            $res[$k]['status_value'] = PopupModel::$statusValue[$v['status']];
            $res[$k]['image'] = WEB_PHOTO_SRC . "/" . $v['image'];
        }

        $page['item_count'] = $this->_popup_mod->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->assign('status_list', array(
            'on'   =>  PopupModel::$statusValue['on'],
            'off'  =>  PopupModel::$statusValue['off'],
        ));
        $this->assign('type_list', array(
            'banner'   =>  PopupModel::$typeValue['banner'],
            'theme'    =>  PopupModel::$typeValue['theme'],
        ));


        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('popup.index.html');

    }

    //添加
    function add(){
        if(!IS_POST){
            $this->assign('yes_or_no', array(
                'on'   =>  PopupModel::$statusValue['on'],
                'off'  =>  PopupModel::$statusValue['off'],
            ));
            $this->assign('typeList', array(
                'banner'   =>  PopupModel::$typeValue['banner'],
                'theme'    =>  PopupModel::$typeValue['theme'],
            ));
            $this->assign('keywordList',array(
                'view_homepage'     => PopupModel::$keywordValue['view_homepage'],
                'view_category'     => PopupModel::$keywordValue['view_category'],
                'view_wish_list'    => PopupModel::$keywordValue['view_wish_list'],
                'view_my'           => PopupModel::$keywordValue['view_my'],
                'view_order_list'   => PopupModel::$keywordValue['view_order_list'],
                'view_goods_list'   => PopupModel::$keywordValue['view_goods_list'],
                'view_banner_list'  => PopupModel::$keywordValue['view_banner_list'],
                'view_theme_list'   => PopupModel::$keywordValue['view_theme_list'],
            ));


            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            $this->display('popup.form.html');
        }else{
            if($_FILES['image']['error'] == 4 && $_FILES['image']['size'] == 0){
                $this->show_warning('请上传图片！');
                return false;
            }
            $data['type'] = $_POST['type'];
            $data['popup_id'] = $_POST['popup_id'];
            $data['status'] = $_POST['status'];
            $data['remark'] = $_POST['remark'];
            $data['keyword'] = $_POST['keyword'];
            $data['k_remark'] = PopupModel::$keywordValue[$data['keyword']];
            if(!$data['type']){
                $this->show_warning('请选择类型！');
                return false;
            }
            if(!$data['popup_id']){
                $this->show_warning('请选择内容！');
                return false;
            }
            if(!$data['status']){
                $this->show_warning('请选择状态！');
                return false;
            }
            if(!$data['keyword']){
                $this->show_warning('请选择显示位置！');
                return false;
            }
            if($this->_popup_mod->get(array("conditions"=>"keyword = '".$data['keyword']."' AND status = 'on'"))){
                $data['status'] = 'off';
            }
            if (!$id = $this->_popup_mod->add($data)) {  //获取id
                $this->show_warning($this->_popup_mod->get_error());
                return;
            }else{
                $this->admin_log(Lang::get('popup'),1);
            }
            /* 处理上传的图片 */
            $logo = $this->_upload($_FILES,'popup');
            if ($logo === false) {
                return;
            }
            $logo && $this->_popup_mod->edit($id, array('image' => $logo)); //将logo地址记下
            $this->show_message('添加成功', 'back_list', 'index.php?app=popup', 'continue_add', 'index.php?app=popup&amp;act=add');
        }
    }

    function _upload($file,$str){
        require_once '../includes/aliyunOss/samples/Common.php';
        $image = $file[$str];
        $imageName = date("YmdHis", time()) . rand(1000,10000);
        $path = 'data/files/mall/popup/'.$str;

        if ($image['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES[$str]); //上传logo
        if (!$uploader->file_info()) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=popup&amp;act=index');
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        if (!$file_path = $uploader->save($path,$imageName)) {   //保存到指定目录，并以指定文件名$ad_id存储
            $this->show_message('上传文件失败！');
            return false;
        }
        $ossClient = new \common;
        $r = $ossClient->putObjectFile('../'.$file_path,$file_path);
        if(!$r['info'] || $r['info']['http_code'] != 200){
            $this->show_message('上传oss失败！');
            return false;
        }
        unlink('../'.$file_path);
        return $file_path;
    }

    function edit(){
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$id) {
            $this->show_warning('no_such_brand');
            return;
        }
        if(!IS_POST){
            $find_data = $this->_popup_mod->find($id);
            if (empty($find_data)) {
                $this->show_warning('no_such_brand');
                return;
            }
            $brand = current($find_data);
            if ($brand['image']) {
                $brand['image'] = WEB_PHOTO_SRC . "/" . $brand['image'];
            }
            /* 显示新增表单 */
            $this->assign('yes_or_no', array(
                'on'   =>  PopupModel::$statusValue['on'],
                'off'  =>  PopupModel::$statusValue['off'],
            ));
            $this->assign('typeList', array(
                'banner'   =>  PopupModel::$typeValue['banner'],
                'theme'    =>  PopupModel::$typeValue['theme'],
            ));
            $this->assign('keywordList',array(
                'view_homepage'     => PopupModel::$keywordValue['view_homepage'],
                'view_category'     => PopupModel::$keywordValue['view_category'],
                'view_wish_list'    => PopupModel::$keywordValue['view_wish_list'],
                'view_my'           => PopupModel::$keywordValue['view_my'],
                'view_order_list'   => PopupModel::$keywordValue['view_order_list'],
                'view_goods_list'   => PopupModel::$keywordValue['view_goods_list'],
                'view_banner_list'  => PopupModel::$keywordValue['view_banner_list'],
                'view_theme_list'   => PopupModel::$keywordValue['view_theme_list'],
            ));

            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));

            $type = $brand['type'].'_setting';
            $model = &m($type);
            $list = $model->find(array("conditions"=>"preview = 1"));
            foreach($list as $k=>$v){
                if($brand['type'] == 'banner'){
                    $list[$k]['title'] = $v['banner_remark'];
                    $list[$k]['popup_id'] = $v['banner_id'];
                }else{
                    $list[$k]['title'] = $v['theme_title'];
                    $list[$k]['popup_id'] = $v['theme_id'];
                }
            }
            $this->assign('list',$list);
            $this->assign('info', $brand);
            $query['type'] = $brand['type'];
            $query['keyword'] = $brand['keyword'];
            $this->assign('query',$query);
            $this->display('popup.form.html');
        }else{
            $find_data     = $this->_popup_mod->find($id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_theme');
                return;
            }
            $data = array();
            $data['type'] = $_POST['type'];
            $data['popup_id'] = $_POST['popup_id'];
            $data['status'] = $_POST['status'];
            $data['remark'] = $_POST['remark'];
            $data['keyword'] = $_POST['keyword'];
            $data['k_remark'] = PopupModel::$keywordValue[$data['keyword']];
            if(!$data['type']){
                $this->show_warning('请选择类型！');
                return false;
            }
            if(!$data['popup_id']){
                $this->show_warning('请选择内容！');
                return false;
            }
            if(!$data['status']){
                $this->show_warning('请选择状态！');
                return false;
            }
            if(!$data['keyword']){
                $this->show_warning('请选择显示位置！');
                return false;
            }
            if($_FILES){
                //删除原图片
                if($_FILES['image'] && $find_data['image'] && $find_data['image'] != $_FILES['image']){
                    if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['image'])){
                        unlink(WEB_PHOTO_SRC . '/' . $find_data['image']);
                    }
                }

                $logo =   $this->_upload($_FILES,'popup');
                $logo && $data['image'] = $logo;
                if ($logo === false)
                {
                    return;
                }
            }
            if($this->_popup_mod->get(array("conditions"=>"keyword = '".$data['keyword']."' AND status = 'on'"))){
                $data['status'] = 'off';
            }
            $rows = $this->_popup_mod->edit($id, $data);
            if ($this->_popup_mod->has_error()) {
                $this->show_warning($this->_popup_mod->get_error());
                return;
            }else{
                $this->admin_log(Lang::get('popup'),1);
            }

            $this->show_message('保存成功', 'back_list', 'index.php?app=popup', '再次编辑', 'index.php?app=popup&amp;act=edit&amp;id=' . $id);
        }
    }

    function drop() {
        $brand_ids = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$brand_ids) {
            $this->show_warning('网络错误！');

            return;
        }
        $brand_ids = explode(',', $brand_ids);
        $this->_popup_mod->drop($brand_ids);
        if ($this->_popup_mod->has_error()) {    //删除
            $this->show_warning($this->_popup_mod->get_error());
            return;
        }else{
            $this->admin_log(Lang::get('drop_popup'),1);
        }

        $this->show_message('删除成功！');
    }

    /**
     *    处理上传标志
     *
     *    @author    Hyber
     *    @param     int $brand_id
     *    @return    string
     */
//    function _upload_logo($brand_id) {
//        $file = $_FILES['image'];
//
//        if ($file['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
//            return '';
//        }
//        import('uploader.lib');             //导入上传类
//        $uploader = new Uploader();
//        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
//        $uploader->addFile($_FILES['image']); //上传logo
//        if (!$uploader->file_info()) {
//            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=popup&amp;act=edit&amp;id=' . $brand_id);
//            return false;
//        }
//        /* 指定保存位置的根目录 */
//        $uploader->root_dir(ROOT_PATH);
//
//        /* 上传 */
//        if ($file_path = $uploader->save('data/files/mall/popup', $brand_id.rand(10000,99999))) {   //保存到指定目录
//            return $file_path;
//        } else {
//            return false;
//        }
//    }

    //请求banner或者theme接口数据
    function getList(){

        $type = $_POST['typeValue'].'_setting';
        $model = &m($type);

        $list = $model->find(array("conditions"=>"preview = 1"));

        if(empty($list)){
            echo json_encode(array('code'=>-1));
            exit();
        }
        foreach($list as $k=>$v){
            if($_POST['typeValue'] == 'banner'){
                $list[$k]['title'] = $v['banner_remark'];
                $list[$k]['popup_id'] = $v['banner_id'];
            }else{
                $list[$k]['title'] = $v['theme_title'];
                $list[$k]['popup_id'] = $v['theme_id'];
            }
        }
        echo json_encode(array("code"=>1,'data'=>$list));
        exit();
    }
}
